package com.itheima.jdsearch.service;

import com.itheima.jdsearch.config.EsClientConfig;
import com.itheima.jdsearch.pojo.GoodInfo;
import com.itheima.jdsearch.pojo.PageResult;
import com.itheima.jdsearch.utils.ElasticUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @作者 itcast
 * @创建日期 2020/11/21 17:42
 **/
@Service
public class SearchService {

    @Autowired
    ElasticUtils<GoodInfo> elasticUtils;

    public PageResult<GoodInfo> search(String keyword,
                                       Integer page,Integer pageSize,
                                       String price,String sort,boolean order){
        // 参数判断
        // 构建查询参数
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",keyword));
        // 价格区间查询
        if(!StringUtils.isEmpty(price)){
            String[] priceArr = price.split("-");
            RangeQueryBuilder range = QueryBuilders.rangeQuery("price");
            if(priceArr!=null && priceArr.length > 0){
                range.gte(priceArr[0]);
            }
            if(priceArr!=null && priceArr.length > 1){
                range.lte(priceArr[1]);
            }
            boolQueryBuilder.filter(range);
        }
        searchSourceBuilder.query(boolQueryBuilder);
        // 分页信息
        searchSourceBuilder.from(page);
        searchSourceBuilder.size(pageSize);
        // 按照价格降序排序
        if(!StringUtils.isEmpty(sort)){
            searchSourceBuilder.sort(sort, order? SortOrder.ASC:SortOrder.DESC);
        }
        // title字段高亮处理
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        PageResult<GoodInfo> searchResult = elasticUtils.search(searchSourceBuilder);
        // 计算有多少页
        Long total = searchResult.getTotal(); //总页数
        Long pages = total%pageSize == 0 ? total/pageSize : total/pageSize + 1;
        searchResult.setPages(pages);
        return searchResult;
    }
}
